import {observable, action} from 'mobx';
import {message} from 'antd';
import {WeaTools} from 'ecCom';

export default class PortalMenuStore {
    // 加载状态
    @observable loading = false;

    // 基本信息
    _menuType = '';
    _resourceId = 1;
    _resourceType = 1;
    _subCompany = {subCompanyId: 1, subCompanyName: ''};
    @observable menuType = this._menuType;
    @observable resourceId = this._resourceId;
    @observable resourceType = this._resourceType;
    @observable subCompany = this._subCompany;

    // 树
    _treeData = [];
    _checkedKeys = [];
    _halfCheckedKeys = [];
    _unCheckedKeys = [];
    _expandedKeys = [];
    @observable treeData = this._treeData;
    @observable checkedKeys = this._checkedKeys;
    @observable halfCheckedKeys = this._halfCheckedKeys;
    @observable unCheckedKeys = this._unCheckedKeys;
    @observable expandedKeys = this._expandedKeys;

    // 同步
    @observable syncDialogVisible = false;
    @observable syncData = {};

    // 自定义菜单编辑
    @observable e4cDialogVisible = false;
    @observable e4cDialogTitle = '';
    @observable e4cData = {};

    // 系统菜单编辑
    @observable e4sDialogVisible = false;
    @observable e4sDialogTitle = '';
    @observable e4sData = {};

    // 共享
    @observable shareObj = {};
    @observable shareDialogVisible = false;
    @observable shareDialogTitle = '';
    @observable shareSessionKey = '';

    @action
    init(params = {}) {
        // 切换前后端菜单时, 改变菜单类型, 并重置store
        this.menuType = params.menuType;
        this.resourceId = this._resourceId;
        this.resourceType = this._resourceType;
        this.subCompany = this._subCompany;

        this.treeData = this._treeData;
        this.checkedKeys = this._checkedKeys;
        this.halfCheckedKeys = this._halfCheckedKeys;
        this.unCheckedKeys = this._unCheckedKeys;
        this.expandedKeys = this._expandedKeys;

        this.getTreeData();
    }

    @action
    getTreeData(parentId = 0, parentIds = null) {
        //this.loading = true;
        WeaTools.callApi('/api/portal/portalmenumaint/treedata', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            parentId: parentId
        }).then(data => {
            let treeData = [...this.treeData];

            if (parentId == 0) {
                treeData = data;
            } else {
                const loop = (treeData) => {
                    for (let i = 0, len = treeData.length; i < len; i++) {
                        const item = treeData[i];

                        if (item.id == parentId) {
                            if (data && data.length) {
                                item.isLeaf = false;
                                item.children = data;
                            } else {
                                item.isLeaf = true;
                                item.children = [];
                            }
                            break;
                        } else {
                            const children = item.children;
                            if (children && children.length) {
                                loop(children);
                            }
                        }
                    }
                };
                loop(treeData);
            }

            const checkedKeys = [...this.checkedKeys];
            const halfCheckedKeys = [...this.halfCheckedKeys];
            const loop2 = (treeData) => {
                for (let i = 0, len = treeData.length; i < len; i++) {
                    const item = treeData[i];
                    const children = item.children;

                    if (item.checked) {
                        checkedKeys.push(item.key);
                    }

                    if (children && children.length) {
                        loop2(children);
                    }
                }
            };
            loop2(treeData);

            // checkedKeys去重
            let checkedKeysUnique = [], hash = {};
            for (let i = 0, element; (element = checkedKeys[i]) != null; i++) {
                if (!hash[element]) {
                    checkedKeysUnique.push(element);
                    hash[element] = true;
                }
            }

            this.treeData = treeData;
            this.checkedKeys = checkedKeysUnique;
            this.halfCheckedKeys = halfCheckedKeys;
            if (parentIds) {
                this.expandedKeys = parentIds;
            }
            //this.loading = false;
        });
    }

    @action
    setExpandedKeys(expandedKeys) {
        this.expandedKeys = expandedKeys;
    }

    @action
    setCheckedKeys(checkedKeys, checked, key) {
        if (checked) { // 选中, 将该项从未选中去除
            let unCheckedKeys = this.unCheckedKeys;
            let _unCheckedKeys = [];
            for (let i = 0, len = unCheckedKeys.length; i < len; i++) {
                const item = unCheckedKeys[i];
                if (item != key) {
                    _unCheckedKeys.push(item);
                }
            }
            this.unCheckedKeys = _unCheckedKeys;
        } else { // 未选中, 将该项添加到未选
            this.unCheckedKeys.push(key)
        }

        this.checkedKeys = checkedKeys.checked;
        this.halfCheckedKeys = checkedKeys.halfChecked;
    }

    @action
    selectSubCompany(subCompany) {
        this.subCompany = subCompany;

        const subCompanyId = subCompany.subCompanyId;
        if (subCompanyId != 0) {
            this.resourceId = subCompanyId;
            this.resourceType = 2;
        } else {
            this.resourceId = 1;
            this.resourceType = 1;
        }

        // 切换分部时, 重置菜单树
        this.treeData = this._treeData;
        this.checkedKeys = this._checkedKeys;
        this.halfCheckedKeys = this._halfCheckedKeys;
        this.unCheckedKeys = this._unCheckedKeys;
        this.expandedKeys = this._expandedKeys;

        this.getTreeData();
    }

    @action
    treeSave() {
        WeaTools.callApi('/api/portal/portalmenumaint/treesave', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            checkedIds: this.checkedKeys.join(','),
            unCheckedIds: this.unCheckedKeys.join(',')
        }).then(data => {
            if (data.result) {
                message.success('保存成功！');
            } else {
                message.warning('保存失败！');
            }
        });
    }

    @action
    orderSave(params = {}) {
        const tarMenuId = params.tarMenuId;
        const curMenuId = params.curMenuId;

        WeaTools.callApi('/api/portal/portalmenumaint/ordersave', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            tarMenuId: tarMenuId,
            curMenuId: curMenuId
        }).then(data => {
            if (data.result) {
                message.success('保存成功！');
            } else {
                message.warning('保存失败！');
            }
        });
    }

    @action
    syncPortalMenu(menu = {}) {
        const {id = ''} = menu;

        this.syncDialogVisible = true;
        this.syncData = {
            menuId: id,
            subCompanyIds: '',
            syncOrder: false,
            syncChecked: false,
            syncNewMenu: false,
            syncRight: false,
            syncRightType: '1'
        }
    }

    @action
    syncCancel() {
        this.syncDialogVisible = false;
    }

    @action
    syncChange(field, value) {
        this.syncData[field] = value;
    }

    @action
    syncSave() {
        WeaTools.callApi('/api/portal/portalmenumaint/syncsave', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            ...this.syncData
        }).then(data => {
            if (data.result) {
                message.success('同步成功！');
                this.syncCancel();
            } else {
                message.warning('同步失败！');
            }
        });
    }

    @action
    addCustomMenu(params = {}) {
        const {to = 'subCompany', menu = {}} = params;
        const {id = '', name = ''} = menu;

        WeaTools.callApi('/api/portal/portalmenumaint/addcustommenu', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            id: id
        }).then(data => {
            let parentId = 0;
            let editDialogTitle = '添加子菜单:';

            if (to == 'subCompany') {
                parentId = 0;
                editDialogTitle += data.title;
            } else if (to == 'menu') {
                parentId = id;
                editDialogTitle += name;
            }

            this.e4cDialogVisible = true;
            this.e4cDialogTitle = editDialogTitle;
            this.e4cData = {
                id: 0,
                parentId: parentId,
                customName: '',
                customName_e: '',
                customName_t: '',
                topmenuname: '',
                topname_e: '',
                topname_t: '',
                linkMode: 'normal',
                linkAddress: '',
                baseTarget: '',
                iconUrl: '',
                topIconUrl: '',
                syncType: '0',
                subCompanyIds: ''
            };
        });
    }

    @action
    editCustomMenu(id) {
        WeaTools.callApi('/api/portal/portalmenumaint/editcustommenu', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            id: id
        }).then(data => {
            this.e4cDialogVisible = true;
            this.e4cDialogTitle = '编辑菜单:' + data.customName;
            this.e4cData = data;
        });
    }

    @action
    editCustomMenuCancel() {
        this.e4cDialogVisible = false;
    }

    @action
    editCustomMenuChange(field, value) {
        this.e4cData[field] = value;
    }

    @action
    editCustomMenuSave() {
        WeaTools.callApi('/api/portal/portalmenumaint/custommenusave', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            subCompanyId: this.subCompany.subCompanyId,
            ...this.e4cData
        }).then(data => {
            if (data.result) {
                message.success('保存成功！');
                this.editCustomMenuCancel();
                this.getTreeData(this.e4cData.parentId, data.parentIds);
            } else {
                message.warning('保存失败！');
            }
        });
    }

    @action
    deleteCustomMenu(id, parentId, isall) {
        WeaTools.callApi('/api/portal/portalmenumaint/deletecustommenu', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            id: id,
            isall: isall
        }).then(data => {
            if (data.result) {
                message.success('删除成功！');
                this.getTreeData(parentId, data.parentIds);
            } else {
                message.warning('删除失败！');
            }
        });
    }

    @action
    editSystemMenu(id) {
        WeaTools.callApi('/api/portal/portalmenumaint/editsystemmenu', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            id: id
        }).then(data => {
            this.e4sDialogVisible = true;
            this.e4sDialogTitle = '编辑菜单:' + data.customName;
            this.e4sData = data;
        });
    }

    @action
    editSystemMenuCancel() {
        this.e4sDialogVisible = false;
    }

    @action
    editSystemMenuChange(field, value) {
        this.e4sData[field] = value;
    }

    @action
    editSystemMenuSave() {
        WeaTools.callApi('/api/portal/portalmenumaint/systemmenusave', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            ...this.e4sData
        }).then(data => {
            if (data.result) {
                message.success('保存成功！');
                this.editSystemMenuCancel();
                this.getTreeData(this.e4sData.parentId, data.parentIds);
            } else {
                message.warning('保存失败！');
            }
        });
    }

    @action
    getShareList(menu) {
        const {id, name} = menu;

        this.shareObj = {infoid: id};
        this.shareDialogVisible = true;
        this.shareDialogTitle = '使用限制:' + name;

        WeaTools.callApi('/api/portal/portalmenushare/list', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            infoid: id
        }).then(data => {
            this.shareSessionKey = data.sessionkey;
        });
    }

    @action
    shareCancel() {
        this.shareDialogVisible = false;
    }

    @action
    shareSave(shareObj, shareData, callback) {
        WeaTools.callApi('/api/portal/portalmenushare/save', 'POST', {
            menuType: this.menuType,
            resourceId: this.resourceId,
            resourceType: this.resourceType,
            ...shareObj,
            ...shareData
        }).then(data => {
            if (data.result) {
                message.success('保存成功！');
                this.getShareList(shareObj.infoid);
                callback();
            } else {
                message.warning('保存失败！');
            }
        });
    }

    @action
    shareDelete(shareObj, ids) {
        if (ids) {
            WeaTools.callApi('/api/portal/portalmenushare/delete', 'POST', {
                menuType: this.menuType,
                resourceId: this.resourceId,
                resourceType: this.resourceType,
                ids: ids
            }).then(data => {
                if (data.result) {
                    this.getShareList(shareObj.infoid);
                }
            });
        }
    }
}
